<?php
require_once ( 'TVB/MSApi/Client/requires.php' ) ;
$page = 0 ;
$limit = 50 ;
require_once ( 'TVB/Entity/MemberBrowseHistoryEntity.php' ) ;

$signature = array_key_exists('member_id', $_REQUEST)?$_REQUEST['member_id']:'' ;
$obj = new MSApiClient();
$member_id = base64_encode(urldecode($signature));
$result = $obj->restRequest('Member','checkLoginByCookie', array('cookie' => $member_id));
$login_id = (empty($result->result->login_id)) ? 'guest' : (string)$result->result->login_id ;
$action = array_key_exists('action', $_REQUEST)?$_REQUEST['action']:'view' ;

if ( $login_id == 'guest' ) {
	$tmp='<ul class="mytvplus-my-playlist-items">';
	$tmp = '</ul>' ;
	$data2 = json_encode($tmp);
	echo $_GET['jsonp_callback'] . '(' . $data2 . ');';
	return ;
}


$entity = new MemberBrowseHistoryEntity($login_id ) ;


if ( $action == 'add' ) {
	$url = array_key_exists ('url', $_REQUEST)?$_REQUEST['url']:'' ;
	$video_title = array_key_exists('video_title', $_REQUEST)?$_REQUEST['video_title']:'' ;
	$video_id = array_key_exists('video_id',$_REQUEST)?$_REQUEST['video_id']:'' ;
	$programme_id = array_key_exists('programme_id', $_REQUEST)?$_REQUEST['programme_id']:'' ;

    $sample_obj = array ('datetime' => '', 'url' => '', 'video_title' => '', 'video_id' => '', 'programme_id' => '') ;
 
    $entity_record = array_intersect_key( $_REQUEST, $sample_obj ) ;
	$entity_record['datetime'] = time() ;
	$entity->insert ( $entity_record ) ;

	$result = array ( 'status' => 1, 'description' => 'add history success') ;
	echo $_GET['jsonp_callback'] . '(' . json_encode($result) . ');';
	return ;

} else if ($action == 'delete' ) {
	$video_id = array_key_exists('video_id',$_REQUEST)?$_REQUEST['video_id']:'' ;
	$query = "delete from history where video_id = '".$video_id."'" ;	
	$entity->exec( $query ) ;	
	$result = array ( 'status' => 1, 'description' => 'remove history success') ;
	echo $_GET['jsonp_callback'] . '(' . json_encode($result) . ');';
	return ;
} else if ( $action == 'delete_all' ) {
	$query = "delete from history" ;	
	$entity->exec( $query ) ;	
	$result = array ( 'status' => 1, 'description' => 'remove history success') ;
	echo $_GET['jsonp_callback'] . '(' . json_encode($result) . ');';
	return ;
} else {
	$data = $entity->selectByQuery ( "select * from history where video_title != 'NULL' group by url order by datetime desc limit {$page},{$limit}" ) ;

$tmp='<ul class="mytvplus-my-playlist-items">';
foreach ($data as $history ) {
	$expire = (array_key_exists('expired', $history) && $history['expired']) ?  'expired' : '';
	$free = (array_key_exists('free', $history) && $history['free']) ? ' free' : '';
	$tmp = $tmp.'<li class="'.$expire.$free.'"><a class="remove" href="#" rel="his-'.$history['video_id'].'">-</a><h5><a href="'.$history['url'].'">'.$history['video_title'].'</a></h5></li>';
}
$tmp = $tmp. '</ul>';

$data2 = json_encode($tmp);
echo $_GET['jsonp_callback'] . '(' . $data2 . ');';
return ;
}

?>

